package com.wecan.web.security;

import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import com.wecan.api.saasdata.UserData;
import com.wecan.base.constants.RedisKey;
import com.wecan.cache.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author liuzhihao
 * @Date 2022.01.22
 * @Version ${version}
 * @Description ${description}
 */
public class StpInterfaceImpl implements StpInterface {

    @Autowired
    UserData userData;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        if (loginId == null) {
            return new ArrayList<>();
        }
        long userId = Long.parseLong((String) loginId);
        List<Integer> roleIds = (List<Integer>) redisUtil.get(RedisKey.USER_ROLE + userId);
        if (roleIds == null) {
            roleIds = userData.loadUserRoles(userId);
            redisUtil.set(RedisKey.USER_ROLE + userId, roleIds, RedisKey.USER_PERMISSION_EXPIRE_TIME);
        }
        Set<String> permissions = new HashSet<>();
        Map<String, Object> rolePmap = redisUtil.keysGet(RedisKey.ROLE_PERMISSION);
        roleIds.forEach(id -> {
            List<Integer> pers = (List<Integer>) rolePmap.get(String.valueOf(id));
            if (pers != null) {
                pers.forEach(item -> permissions.add(String.valueOf(item)));
            }
        });
        return permissions.parallelStream().collect(Collectors.toList());
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        return null;
    }
}
